﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using Innovox.YDeviceLib;

namespace FS_Config
{
    /// <summary>
    /// Interaction logic for FirmwareUpgradeWindow.xaml
    /// </summary>
    public partial class FirmwareUpgradeWindow : Window
    {
        YNetManager _ynet;
        DateTime startTime;

        public FirmwareUpgradeWindow(YNetManager netMan, List<YDevice> devices, string filename)
        {
            InitializeComponent();
			//y1gUpdateGroupBox.IsEnabled = false;
			closeButton.IsEnabled = false;
            _ynet = netMan;
            _ynet.YNetUpgradeComplete += UpgradeCompleted;
            _ynet.YNetUpgradeProgress += Progressed;
           // _ynet.BeginUpgrade(devices, filename);
			filenameTextBox.Text = filename;
            startTime = DateTime.Now;
        }

        private void UpgradeCompleted(object sender, YNetUpgradeCompletedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                _ynet.YNetUpgradeComplete -= UpgradeCompleted;
                _ynet.YNetUpgradeProgress -= Progressed;
				closeButton.IsEnabled = true;

                DateTime te = DateTime.Now;
                TimeSpan elapseTime = te - startTime;
                y1gUpgradeProgressBar.Value = 100;
                upgradeLogListView.Items.Add("Upgrade Completed in " + elapseTime.ToString());
                //this.Close();
            });
        }

        private void Progressed(object sender, YNetUpgradeProgressEventArgs e)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                YNetManager yman = (YNetManager)sender;
				if (e.Success)
					y1gUpgradeProgressBar.Value = e.Percent;
				else
				{
                    YDevice dev = e.Device;

                    string err = "Error programming: " + dev.Name + "@ " + dev.Ip.ToString();
					upgradeLogListView.Items.Add(err);
				}
            });
        }

		private void closeButton_Click(object sender, RoutedEventArgs e)
		{
			Close();
		}

    }
}
